package com.greendragon.web.action.admin; 

import java.util.Date;

import org.apache.commons.lang.StringUtils;

import com.greendragon.control.constant.GlobalConstants;
import com.greendragon.persistence.domain.User;
import com.greendragon.persistence.enmu.UserRoleType;
import com.greendragon.service.backend.IUserBackendService;
import com.greendragon.util.EncryptionUtil;
import com.greendragon.web.action.BaseAction;

/** 
 * @author wulibin, exceptsky@gmail.com, 2012-1-12 下午01:34:13
 * 
 */
public class AccountAction extends BaseAction{
	private static final long serialVersionUID = -4438685104803843091L;
	private IUserBackendService 	userService;
	
	private Long					uid;										//用户ID
	/*添加新用户资料 */
    private String                 	name;                                   	// 用户名
    private String                 	password;                                	// 密码
    private String                 	confirmPassword;                         	// 确认密码
    private String                 	nickname;                             		// 昵称
    private String                 	website;                             		// 网址
    private String                 	phone;                             			// 固定电话
    private String 					role;										// 角色
    private boolean					sendPassword;								// 是否发送密码
    /*修改用户资料 */
    private String                 	cellphone;                             		// 手机电话
    private String					qq;											// qq
    private String					email;										// 邮箱
    private String					question;
    private String					answer;
    /*修改密码 */
    private String                 	oldpw;                         				// 旧密码
    
    private User					targetUser;									//修改密码时的对象用户
    public String profile()throws Exception{
    	User loginUser = (User)getSession().get(GlobalConstants.SESSION_LOGIN_USER);
    	if(null != loginUser && (null == uid || uid.longValue() == loginUser.getId())){
    		//当前登入的管理员用户
    		setUserInfo(loginUser);
    	}else{
    		//其他用户
    		setUserInfo(userService.get(uid));
    	}
    	return SUCCESS;
    }
    
    public String update()throws Exception{
    	User loginUser = (User)getSession().get(GlobalConstants.SESSION_LOGIN_USER);
    	User user;
    	if( null!=loginUser && uid.longValue()==loginUser.getId().longValue()){	//当前登入的管理员用户
    		user = loginUser;
    	}else{
    		user = userService.get(uid);
    		if(null == user){
    			addFieldError("uid", getText("uid.invalid"));
    			return INPUT;
    		}
    	}
    	if(StringUtils.isNotBlank(answer)){
    		user.setSecurityQuestion(question);
			user.setSecurityAnswer(answer);
    	}
    	user.setDisplayName(nickname);
    	user.setCellphone(cellphone);
    	user.setPhone(phone);
    	user.setQq(qq);
    	user.setWebsite(website);
    	user.setEmail(email);
    	user.setRole(UserRoleType.getByName(role).getName());
    	user.setLastLoginAt(new Date());
    	user.setLastLoginIp(getRequest().getRemoteHost());
    	user.setGravatarHash(EncryptionUtil.encodeMD5(email));
    	userService.update(user);
    	if(null != loginUser && uid.longValue() == loginUser.getId().longValue()){
    		getSession().put(GlobalConstants.SESSION_LOGIN_USER, user);
    	}
    	return SUCCESS;
    }
    
    public String changePassword()throws Exception{
    	User loginUser = (User)getSession().get(GlobalConstants.SESSION_LOGIN_USER);
    	if(null == targetUser){
    		if(null != loginUser && uid.longValue() == loginUser.getId()){
    			targetUser = loginUser;
    		}else{
    			targetUser = userService.get(uid);
    		}
    	}
    	targetUser.setPassword(EncryptionUtil.encodeMD5(password));
		userService.update(targetUser);
		if(null != loginUser && uid.longValue() == loginUser.getId()){
			//登入用户
			getSession().put(GlobalConstants.SESSION_LOGIN_USER, targetUser);
		}
    	return SUCCESS;
    }
    
    public String delete()throws Exception{
    	return SUCCESS;
    }
    
	public String register()throws Exception{
		 User user = userService.getByName(name);
	        if (null != user) {
	            // 该email已经被注册
	            addFieldError("name", getText("register.email.fail"));
	            return INPUT;
	        } else {
	            user = new User();
	            user.setName(name);
	            user.setPassword(password);
	            user.setDisplayName(nickname);
	            user.setEmail(name);
	            user.setWebsite(website);
	            user.setPhone(phone);
	            user.setActive(true);
	            user.setBlock(false);
	    		user.setCreatedAt(new Date());
	    		user.setLastLoginAt(new Date());
	            user.setCreatedIp(getRequest().getRemoteHost());
	            user.setLastLoginIp(getRequest().getRemoteHost());
	            user.setRole(UserRoleType.getByName(role).getName());
	            user.setGravatarHash(EncryptionUtil.encodeMD5(user.getEmail()));
	            userService.register(user);
	            
	            if(true == sendPassword){
					/*TODO send password*/
				}
				return SUCCESS;
	        }
	}
	
	
    
    public void validateChangePassword(){
    	if(null != uid){
    		User loginUser = (User)getSession().get(GlobalConstants.SESSION_LOGIN_USER);
    		if(uid.longValue() == loginUser.getId().longValue()){
    			targetUser = loginUser;
    		}else{
    			targetUser = userService.get(uid);
    		}
    		//设置当前用户信息
    		setUserInfo(targetUser);
    		//管理员，需要校验旧密码
    		if(targetUser.getRole().equalsIgnoreCase(UserRoleType.ADMIN.getName())){
    			//空
    			if( StringUtils.isBlank(oldpw)){
    				addFieldError("oldpw", getText("password.required"));
    				return;
    			}
    			//长度4~20
    			if(oldpw.length()<6 || oldpw.length()>20){
    				addFieldError("oldpw", getText("password.range"));
    				return;
    			}
    			//旧密码是否正确
    			String oldpwMd5 = EncryptionUtil.encodeMD5(oldpw);
    			if(!oldpwMd5.equalsIgnoreCase(targetUser.getPassword())){
    				addFieldError("oldpw", getText("password.oldpassword.error"));
    				return;
    			}
    		}
    		//校验新密码
    		//空
    		if(StringUtils.isBlank(password)){
    			addFieldError("password", getText("password.required"));
				return;
    		}
    		//长度4~20
			if(password.length()<6 || password.length()>20){
				addFieldError("password", getText("password.range"));
				return;
			}
    		//校验确认密码
    		//空
    		if(StringUtils.isBlank(confirmPassword)){
    			addFieldError("confirmPassword", getText("password.required"));
				return;
    		}
    		//长度4~20
			if(confirmPassword.length()<6 || confirmPassword.length()>20){
				addFieldError("confirmPassword", getText("password.range"));
				return;
			}
			//确认密码等于新密码
			if(!confirmPassword.equalsIgnoreCase(password)){
    			addFieldError("confirmPassword", getText("password.confirm.error"));
				return;
    		}
    	}else{
    		addFieldError("uid", getText("uid.required"));
    	}
    }
    
    public void validateupdate(){
    	if(null != uid){
    		
    	}else{
    		addFieldError("uid", getText("uid.required"));
    	}
    }
    private void setUserInfo(User user){
    	if(null != user){
    		this.uid = user.getId();
    		this.name = user.getName();
    		this.nickname = user.getDisplayName();
    		this.email = user.getEmail();
    		this.website = user.getWebsite();
    		this.phone = user.getPhone();
    		this.cellphone = user.getCellphone();
    		this.qq = user.getQq();
    		this.question = user.getSecurityQuestion();
    		this.answer = user.getSecurityAnswer();
    		this.role = user.getRole();
    	}else{
    		this.uid = null;
    		this.name = null;
    	}
    }

	public IUserBackendService getUserService() {
		return userService;
	}


	public void setUserService(IUserBackendService userService) {
		this.userService = userService;
	}


	public String getName() {
		return name;
	}


	public void setName(String name) {
		this.name = name;
	}


	public String getPassword() {
		return password;
	}


	public void setPassword(String password) {
		this.password = password;
	}


	public String getConfirmPassword() {
		return confirmPassword;
	}


	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}


	public String getNickname() {
		return nickname;
	}


	public void setNickname(String nickname) {
		this.nickname = nickname;
	}


	public String getWebsite() {
		return website;
	}


	public void setWebsite(String website) {
		this.website = website;
	}


	public String getPhone() {
		return phone;
	}


	public void setPhone(String phone) {
		this.phone = phone;
	}


	public String getRole() {
		return role;
	}


	public void setRole(String role) {
		this.role = role;
	}


	public boolean isSendPassword() {
		return sendPassword;
	}


	public void setSendPassword(boolean sendPassword) {
		this.sendPassword = sendPassword;
	}


	public Long getUid() {
		return uid;
	}


	public void setUid(Long uid) {
		this.uid = uid;
	}


	public String getOldpw() {
		return oldpw;
	}


	public void setOldpw(String oldpw) {
		this.oldpw = oldpw;
	}

	public String getCellphone() {
		return cellphone;
	}


	public void setCellphone(String cellphone) {
		this.cellphone = cellphone;
	}


	public String getQq() {
		return qq;
	}


	public void setQq(String qq) {
		this.qq = qq;
	}

	public String getEmail() {
		return email;
	}


	public void setEmail(String email) {
		this.email = email;
	}


	public String getQuestion() {
		return question;
	}


	public void setQuestion(String question) {
		this.question = question;
	}


	public String getAnswer() {
		return answer;
	}

	public void setAnswer(String answer) {
		this.answer = answer;
	}
}
 